package com.flightgame.controllers;

import java.io.IOException;
import java.io.Writer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.flightgame.hibernate.User;
import com.flightgame.hibernate.UserDao;
import com.flightgame.services.GameServices;
import com.flightgame.services.JSONServices;
import com.flightgame.tools.Utils;

@Controller
@RequestMapping("/game")
public class GameController {
	
	@Autowired
	private GameServices gameServices;
	@Autowired
	private JSONServices jsonServices;
	@Autowired
	private UserDao userDao;
	@Autowired
	private Utils utils;
	
	@RequestMapping(value = "/adduser", method = RequestMethod.POST)
	public void addUser(HttpServletRequest request,HttpServletResponse response) throws IOException{
		String username = request.getParameter("username");
		Writer writer = response.getWriter();
		User user = gameServices.addNewUser(username,"");
		
		response.setCharacterEncoding("UTF-8");
		if(user != null) writer.write(jsonServices.getSuccess(true, "",null).toString());
		else writer.write(jsonServices.getSuccess(false, "User Already Exists!",null).toString());
	}
	
	@RequestMapping(value = "/buyitem", method = RequestMethod.POST)
	public void buyItem(HttpServletRequest request,HttpServletResponse response) throws IOException, JSONException{
		String username = request.getParameter("username");
		String itemname = request.getParameter("itemname");
		String lat = request.getParameter("lat");
		String lon = request.getParameter("lon");
		String airportCode = request.getParameter("airportcode");
		Writer writer = response.getWriter();
		JSONObject successJson;
		response.setCharacterEncoding("UTF-8");
		
		int success = gameServices.buyItem(username, itemname, Double.parseDouble(lat),Double.parseDouble(lon),airportCode);
		if(success != utils.SUCCESS){
			successJson = jsonServices.getSuccess(false,utils.getMessage(success),null);
		}
		else{
			JSONObject extraParamsJson = new JSONObject();
			extraParamsJson.put("credits",userDao.getUser(username).getCredits());
			successJson = jsonServices.getSuccess(true,utils.getMessage(success),extraParamsJson);
		}
		
		writer.write(successJson.toString());
	}
	
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public void login(HttpServletRequest request,HttpServletResponse response) throws IOException, JSONException{
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		Writer writer = response.getWriter();

		response.setCharacterEncoding("UTF-8");

		writer.write(jsonServices.getUserDataForLogin(username).toString());
	}
}
